<?php
require '../includes/LITTLE_ChukuExcelReader.class.php';
require '../includes/functions.inc.php';
require_once('../includes/SimpleTableExporter.class.php');

ini_set( "memory_limit" , "128M");
ini_set("max_execution_time",0);

$smarty = SmartyManager::getSmarty();

/*************************************************************
 * 每个上传文件只要修改下面这些变量就基本可以了
 ************************************************************/
$formFilename = 'mainDownloadFile';

//不可缺少的列
$obligatoCols = array(
	'发车证书号','批号','订单号','订单子项号');

//电子表格和数据库表中的列的对应关系
$tableCols = array();

/************************************************************
 * 文件上传
 ***********************************************************/
try{
	//$file 在本程序中用作了全局变量，用来在需要filename的函数中使用
	$file = saveUploadedFile($formFilename);
}catch(Exception $e){
	$smarty->assign('errMsg', $e);
	$smarty->display('error.html');
	exit();
}

try{
	beginTransaction();
	$littleReader = new LITTLE_ExcelReader();
	$littleReader->read($file->getNewPath());

	$littleReader->obligatoColumns = $obligatoCols;
	$littleReader->tableColumns = $tableCols;
	
	$littleReader->checkFirstRow('download');
	
	$consignmentArray = $littleReader->getMainDownloadArray();
	
	//读取第一行数据
	$sheet = $littleReader->getReader()->sheets[0]['cells'];
	$rows = array();
	$firstRow = current($sheet);
	
	//第一行加上‘产品质量证明书号’和‘产品质量证明书编号’两列
	array_push($firstRow,'产品质量证明书号','产品质量证明书编号');
	
	
	foreach ($consignmentArray as $value) {
			$row_download = next($sheet);
			
			//处理空单元格
			$count = count($row_download);
			for($i = 0; $i < $count; $i++){
				if(!isset($row_download[$i+1])){
					$count++;
					$row_download[$i+1] = '';
				}
			}
			
			//从总表一中获取与上传文件中订单号，订单子项号，批号，发车证书号对应的产品质量证明书号和产品质量证明书编号
			$orderNumber = $value[0];
			$orderSubitemNumber = $value[1];
			$batchNumber = $value[2];
			$facheNumber = $value[3];
			$sql = "select certificationNumber, certificationCodification from little_main
			where orderNumber = '$orderNumber' and orderSubitemNumber = '$orderSubitemNumber' and sampleBatch = '$batchNumber' and facheNumber = '$facheNumber' 
			order by certificationNumber asc limit 1;";
			$result = DB::query($sql);
			$row = $result->fetch_array();
			$new_row = array();
			for($i=1;$i<=count($row_download);$i++){
				array_push($new_row,$row_download[$i]);
			}
			array_push($new_row,$row['certificationNumber'],$row['certificationCodification']);
			array_push($rows,$new_row);
	}
	$exp = new SimpleTableExporter();
	$exp->insertDownloadData($rows,$firstRow,'sheet1');
	$exp->export();
}catch(DBQueryException $e){
	$smarty->assign('errMsg', $e);
	$smarty->display('error.html');
	rollback();
	exit();
}catch(Exception $e){
	$smarty->assign('errMsg', $e);
	$smarty->display('error.html');
	rollback();
	exit();
}

commit();
?>